<template>
  <section class="content_box">
    <details-head title="发票管理"
                  close-label="返回" />
    <div class="scroll">
      <el-form class="form_box"
               label-width="100px"
               label-position="right"
               size="small">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item v-if="invoicingType === 1"
                          label="发货方名称"
                          prop="customerName">
              <div>
                <Tooltip v-if="iconName"
                         :content="content"
                         :placement="placement">
                  <icon-svg class-name="iconClass mr5"
                            :icon-name="iconName" />
                </Tooltip>
                {{ invoicingDetail.customerName }}
              </div>
            </el-form-item>
            <el-form-item v-else
                          label="承运方名称"
                          prop="carrierName">
              <div>
                <Tooltip v-if="iconName"
                         :content="content"
                         :placement="placement">
                  <icon-svg class-name="iconClass mr5"
                            :icon-name="iconName" />
                </Tooltip>
                {{ invoicingDetail.carrierName }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="对账单名称"
                          prop="name">
              <div>{{ invoicingDetail.name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="制单时间"
                          prop="createAt">
              <div>{{ invoicingDetail.createAt }}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="说明"
                          prop="desc">
              <div class="descSty">{{ invoicingDetail.desc || "--" }}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="应开发票金额"
                          prop="desc">
              <div>{{ invoicingDetail.totalFee ? returnThousandDigit(invoicingDetail.totalFee, 2) : "0.00" }}元</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="已开发票金额"
                          prop="desc">
              <div>{{ invoicingDetail.invoicedMoney ? returnThousandDigit(invoicingDetail.invoicedMoney, 2) : "0.00" }}元</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="未开发票金额"
                          prop="desc">
              <div>{{ invoicingDetail.unInvoicedMoney ? returnThousandDigit(invoicingDetail.unInvoicedMoney, 2) : "0.00" }}元</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="operational"
           class="table-header">
        <Tooltip v-if="tableData.length > 49"
                 content="一个对账单最多填写50张发票信息"
                 placement="bottom">
          <div>
            <el-button type="primary"
                       disabled
                       @click="handleVisable">新增</el-button>
          </div>
        </Tooltip>
        <el-button v-else
                   type="primary"
                   @click="handleVisable">新增</el-button>
      </div>
      <el-table :data="tableData"
                border
                style="width: 100%; margin: 20px 0">
        <el-table-column type="index"
                         width="50" />
        <template v-for="(item, i) in tableColumn">
          <el-table-column v-if="item.props === 'fileSize'"
                           :key="i"
                           :prop="item.props"
                           :label="item.label"
                           :show-overflow-tooltip="true"
                           :width="'160px'">
            <template slot-scope="scope">
              <el-button v-if="scope.row[item.props]"
                         type="text"
                         @click="handleLooK(scope.row)">
                {{scope.row[item.props]}}
              </el-button>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column v-else-if="item.props === 'invoicingDate'"
                           :key="i"
                           :prop="item.props"
                           :label="item.label"
                           :show-overflow-tooltip="true"
                           :width="'160px'">
            <template slot-scope="scope">
              {{$moment(scope.row[item.props]).format("YYYY-MM-DD")}}
            </template>
          </el-table-column>
          <el-table-column v-else-if="item.props === 'operation'"
                           :key="i"
                           :prop="item.props"
                           :label="item.label"
                           :width="'200px'">
            <template slot-scope="scope">
              <el-button v-if="operational"
                         type="text"
                         @click="editHandel(scope.row)">编辑</el-button>
              <el-button v-if="operational"
                         type="text"
                         @click="deleteHandel(scope.row)">删除</el-button>
              <el-button v-if="scope.row.invoiceFiles"
                         type="text"
                         @click="downHandel(scope.row)">下载</el-button>
              <Tooltip v-else
                       content="暂无发票附件"
                       placement="left">
                <span :style="operational ? 'margin-left: 10px;' : ''">
                  <el-button type="text"
                             disabled>下载</el-button>
                </span>
              </Tooltip>
            </template>
          </el-table-column>
          <el-table-column v-else
                           :key="i"
                           :prop="item.props"
                           :label="item.label"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{scope.row[item.props] || '--'}}
            </template>
          </el-table-column>
        </template>
      </el-table>
      <InvoicingDialog v-if="visible"
                       :visible.sync="visible"
                       :bill-id="billId"
                       :record="record"
                       @submit="getFinanceInvoicingDetail" />
      <el-dialog :visible="lookFilesVisible"
                 :before-close="handleCancel"
                 :close-on-click-modal="false"
                 title="发票文件"
                 width="700px"
                 top="15vh"
                 append-to-body>
        <Attachments :value="invoiceFilesActive" />
      </el-dialog>
    </div>
  </section>
</template>

<script>
import DetailsHead from "@/components/detailsHead/Header";
import Tooltip from "@components/basic/Tooltip.vue";
import InvoicingDialog from "./components/InvoicingDialog.vue";
import Attachments from "@basic/Attachments.vue";
import { returnThousandDigit } from "@/libs/util.js";
import { finance } from "@/api/index";
// import _ from 'lodash'
// import axios from 'axios';
// import JSZip from 'jszip';
// import FileSaver from 'file-saver';
export default {
  name: "FinanceInvoicing",
  components: {
    DetailsHead,
    InvoicingDialog,
    Attachments,
    Tooltip
  },
  data () {
    return {
      returnThousandDigit,
      visible: false,
      lookFilesVisible: false,
      loading: false,
      tableLoading: false,
      tableData: [],
      tableColumn: [
        { label: "发票号码", props: "invoiceNumber" },
        { label: "开票日期", props: "invoicingDate" },
        { label: "发票代码", props: "invoiceCode" },
        { label: "发票金额（元）", props: "invoiceMoney" },
        { label: "发票说明", props: "desc" },
        { label: "发票文件（数量）", props: "fileSize" },
        { label: "操作", props: "operation" }
      ],
      invoicingDetail: {},
      record: {},
      invoiceFilesActive: null
    };
  },
  computed: {
    invoicingType () {
      // 开票类型 1应收 2应付
      const { name } = this.$route
      return ['customerFinanceInvoicing'].includes(name) ? 1 : 2
    },
    billId () {
      const { query } = this.$route;
      return query?.billId ? Number(query?.billId) : null
    },
    operational () {
      const { name } = this.$route
      return name === 'customerFinanceInvoicing' || (name === 'carrierFinanceInvoicing' && this.invoicingDetail?.carrierType === 0)
    },
    placement () {
      return 'top'
    },
    content () {
      if (this.invoicingType === 1) {
        switch (this.invoicingDetail?.customerType) {
          case 0:
            return '线下';
          case 1:
            return '线上';
          default:
            return '';
        }
      } else {
        if (this.invoicingDetail?.carrierType === 0) {
          return '线下';
        }
        if (this.invoicingDetail?.carrierType === 1 && this.invoicingDetail?.carrierExtraType == 0) {
          return '线上';
        }
      }
      return '';
    },
    iconName () {
      if (this.invoicingType === 1) {
        switch (this.invoicingDetail?.customerType) {
          case 0:
            return 'xianxia';
          case 1:
            return 'xianshang';
          default:
            return '';
        }
      } else {
        if (this.invoicingDetail?.carrierType === 0) {
          return 'xianxia';
        }
        if (this.invoicingDetail?.carrierType === 1 && this.invoicingDetail?.carrierExtraType == 0) {
          return 'xianshang';
        }
      }
      return '';
    }
  },
  created () {
    if (this.billId) {
      this.getFinanceInvoicingDetail();
    }
  },
  methods: {
    handleLooK (record) {
      this.invoiceFilesActive = record?.invoiceFiles
      this.lookFilesVisible = true
    },
    handleCancel () {
      this.lookFilesVisible = false;
    },
    handleVisable () {
      if (this.tableData.length > 49) {
        return this.$message.warning("一个对账单最多填写50张发票信息!");
      }
      this.record = {};
      this.visible = true;
    },
    editHandel (row) {
      this.record = row;
      this.visible = true;
    },
    deleteHandel (row) {
      this.$confirm('确定删除发票信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delete(row)
      })
    },
    async delete (row) {
      let { code } = await finance.deleteFinanceInvoicing(this.billId, row.invoiceId);
      if (code === 0) {
        this.getFinanceInvoicingDetail();
        this.$message.success("操作成功！");
      }
    },
    downHandel (row) {
      const files = row?.invoiceFiles
      if (files.length) {
        files.forEach(({ url }) => {
          let newUrl = url.includes('https') ? url : url.replace('http', 'https')
          if (newUrl.includes('.pdf') || newUrl.includes('.PDF')) {
            window.open(newUrl, '_blank');
          } else {
            this.downloadFile({ url: `${url}?response-content-type=application/octet-stream` })
          }
        })
      }
    },
    downloadFile ({ url }) {
      const iframe = document.createElement('iframe');
      iframe.style.display = "none"; // 防止影响页面
      iframe.style.height = 0; // 防止影响页面
      iframe.src = url;
      document.body.appendChild(iframe);
      console.log("===<xx", url, iframe)
      iframe.onload = function () {
        document.body.removeAttribute(iframe)
      }
      // // 5分钟之后删除（onload方法对于下载链接不起作用）
      // setTimeout(() => {
      //   iframe.remove();
      // }, 5 * 60 * 1000);
    },
    // downHandel (row) {
    //   if (row?.invoiceFiles && row?.invoiceFiles.length) {
    //     let array = row.invoiceFiles;
    //     const zip = new JSZip();
    //     let promissArr = [];
    //     array.forEach(element => {
    //       const promiss = this.getFile(element.url).then(data => {
    //         console.log("===>promiss", element.name, data);
    //         zip.file(element.name, data, { binary: true });
    //       })
    //       promissArr.push(promiss);
    //     });

    //     Promise.all(promissArr).then(() => {
    //       console.log("===>下载完成");
    //       zip.generateAsync({ type: "blob" }).then(content => {
    //         console.log("===>生成压缩包");
    //         FileSaver.saveAs(content, `${row.invoiceNumber}.zip`);
    //       })
    //     });
    //   }
    // },
    // getFile (url) {
    //   return new Promise((resolve, reject) => {
    //     axios({
    //       method: "get",
    //       url: url,
    //       responseType: "blob"
    //     })
    //       .then(data => {
    //         resolve(data.data);
    //       })
    //       .catch(err => {
    //         reject(err.toString());
    //       })
    //   })
    // },
    async getFinanceInvoicingDetail () {
      this.tableLoading = true;
      let { data } = await finance.getFinanceInvoicingDetail(this.billId)
        .catch(err => {
          this.tableLoading = false;
        });
      if (data) {
        this.invoicingDetail = data;
        this.tableData = data?.invoices || [];
      }
    },
    back () {   // 返回
      this.$router.back();
    },
  }
};
</script>
<style lang="scss" scoped>
.content_box {
  background: var(--prev-bg-white);
  padding: 20px;
  position: relative;
}
.scroll {
  height: calc(100vh - 200px);
  overflow-y: auto;
}
.form_box {
  padding: 20px;
}
.table-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  margin-right: 12px;
}
.footer-item {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.descSty {
  word-break: break-all;
}
.iconClass {
  width: 14px;
  height: 14px;
}
</style>
